package com.hefan.robot.service;

import com.alibaba.fastjson.JSON;
import com.cat.tiger.util.DateUtils;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.RobotListenerVo;
import com.hefan.live.itf.LiveImOptService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.live.itf.RoomEnterExitOptService;
import com.hefan.robot.bean.LiveRobotCfg;
import com.hefan.robot.configCenter.RobotConfigCenter;
import com.hefan.robot.itf.ExtraRobotService;
import com.hefan.robot.itf.LiveRobotCfgService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * Created by nigle on 2016/12/7.
 */
@Path("/robot")
@Component("extraRobotService")
public class ExtraRobotServiceImpl implements ExtraRobotService {
    @Resource
    ONSProducer onsProducer;
    @Resource
    LiveRobotCfgService liveRobotCfgService;
    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    RoomEnterExitOptService roomEnterExitOptService;
    @Resource
    private RobotConfigCenter robotConfigCenter;
    @Resource
    LiveImOptService liveImOptService;

    private Logger logger = LoggerFactory.getLogger(ExtraRobotServiceImpl.class);

    @GET
    @Path("/scanningTask")
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    @Override
    public void scanningTask() {
        try{
            String now = DateUtils.currentDate(DateUtils.YYYY_MM_DD_HH_MM_SS);
            logger.info("后台配置机器人任务定时扫描--START");
            List<LiveRobotCfg> listCfg = liveRobotCfgService.getRobotCfgList();
            StringBuffer info = new StringBuffer();
            Map<String,String> propty = robotConfigCenter.getPublicConfig();
            String onsEnv = MapUtils.getStrValue(propty, "ons.env", "");
            int countBack = MapUtils.getIntValue(propty, "robot.back.count.speed.min", 200);
            int sizeNum = listCfg == null ? 0 : listCfg.size();
            logger.info("topic:{},countBack:{},查询数据记录条数{}", onsEnv, countBack,sizeNum);
            if( null != listCfg && listCfg.size()>0) {
                for (LiveRobotCfg cfg : listCfg) {
                    if (StringUtils.isNotBlank(cfg.getInfo())) {
                        info.append(cfg.getInfo());
                    }
                    logger.info("cfgID::后台配置任务:{}",JSON.toJSONString(cfg));
                    if(StringUtils.isBlank(cfg.getLiveUuid()) || cfg.getChatRoomId()<=0 || StringUtils.isBlank(cfg.getUserId())) {
                        info.append(now + "参数错误---");
                        liveRobotCfgService.updteRobotCfg(cfg.getId(), 1, 0, info.toString());
                        logger.info("cfgID::{},liveUuid:{},参数错误", cfg.getId(), cfg.getLiveUuid());
                        continue;
                    }
                    if(!livingRedisOptService.isExistsLivingInfo_Hash(cfg.getUserId())){
                        info.append(now + "直播不存在或结束，任务结束---");
                        liveRobotCfgService.updteRobotCfg(cfg.getId(), 1, 0, info.toString());
                        logger.info("cfgID::{},liveUuid:{},直播不存在或结束，任务结束", cfg.getId(), cfg.getLiveUuid());
                        continue;
                    }
                    if(cfg.getRobotNum() < 1){
                        info.append( now + "机器人任务数量不正确---");
                        liveRobotCfgService.updteRobotCfg(cfg.getId(), 1, 0, info.toString());
                        logger.info("cfgID::{},liveUuid:{},机器人任务的数量不正确:{}", cfg.getId(), cfg.getLiveUuid(), cfg.getRobotNum());
                        continue;
                    }
                    long countInRoom = livingRedisOptService.getLivingRobotCount(cfg.getUserId());
                    if (cfg.getType() == 1 && countInRoom == 0) {
                        info.append( now + "无可减少的机器人---");
                        liveRobotCfgService.updteRobotCfg(cfg.getId(), 1, 0, info.toString());
                        logger.info("cfgID::{},liveUuid:{},直播间内已经没有可清除的机器人:{}",cfg.getId() ,cfg.getLiveUuid(),countInRoom);
                        continue;
                    }
                    long countInRedis = livingRedisOptService.getLivingRobotCount();
                    logger.info("cfgID::后台添加机器人时，查询库存：{}，后台设置：{}", countInRedis, cfg.getRobotNum());
                    if (cfg.getType() == 0 && countInRedis < cfg.getRobotNum()) {
                        info.append(now + "机器人库存不够---");
                        liveRobotCfgService.updteRobotCfg(cfg.getId(), 1, 0, info.toString());
                        logger.info("cfgID::{},liveUuid:{},机器人库存{}不足,后台配置:{}", cfg.getId(), cfg.getLiveUuid(), countInRedis, cfg.getRobotNum());
                        continue;
                    }

                    //队列任务，装填机器人，发布相应数量的延时加机器人任务，当前按照正常机器人走（发送点亮及关注）
                    //计算每次延时时间
                    long delayTime = 60*1000/countBack;
                    RobotListenerVo vo = new RobotListenerVo();
                    vo.setInOrOut(cfg.getType()==0?1:0);
                    vo.setAnchId(cfg.getUserId());
                    vo.setLiveUuid(cfg.getLiveUuid());
                    vo.setChatRoomId(cfg.getChatRoomId());
                    //发送延时任务
                    sendMq(vo,delayTime,onsEnv,cfg);
                    //更新任务进度
                    int status = 1;
                    info.append(now + "：开始执行---");
                    int flag = liveRobotCfgService.updteRobotCfg(cfg.getId(), status, 0, info.toString());
                    logger.info("cfgID::{},liveUuid:{},数据更新“{}”行", cfg.getId(), cfg.getLiveUuid(), flag);
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("后台添加机器人定时任务－－执行失败");
        } finally {
            logger.info("后台添加机器人定时任务－－end");
        }
    }

    @Async
    private void sendMq(RobotListenerVo vo,long delayTime,String onsEnv,LiveRobotCfg cfg){
        for (int i = 0; i < cfg.getRobotNum(); i++) {
            Message message = new Message();
            vo.setInfo("机器人消费过滤主播ID：" + cfg.getUserId() + "后台机器人任务ID：" + cfg.getId()  +  "，本次第" + i + "个");
            message.put("vo", JSON.toJSONString(vo));
            message.setTopic(TopicRegistry.HEFAN_ROBOT_ENTER_EXIT_DELAY);
            message.setTag(onsEnv);
            boolean b = onsProducer.sendDelayMsg(message, i*delayTime);
            logger.info("后台机器人任务，进出值：{}，发送至直播:{}进出任务ID{}：第{}个,delayTime:{}", vo.getInOrOut() == 1 ? "进入" : "离开",cfg.getLiveUuid(), cfg.getId(), String.valueOf(i), delayTime * i);
            if (!b) {
                logger.error("发送队列任务失败！！！{}",i);
            }
        }
    }

    @GET
    @Path("/test")
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    @Override
    public String test(@QueryParam("liveUuid") String liveUuid,@QueryParam("chatRoomId") int chatRoomId) {
        String s = "hihihihihi";
        try {

        } catch (Exception e) {
            logger.info("test unsuccess！");
        }
        return s;
    }

    @GET
    @Path("/index")
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    @Override
    public String index() {
        return "success";
    }

}
